home *** CD-ROM | disk | FTP | other *** search
/ Games of Daze / Infomagic - Games of Daze (Summer 1995) (Disc 1 of 2).iso / x2ftp / msdos / source / snip9503 / commafmt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-03-14  |  1.9 KB  |  84 lines

  1. /*
  2. **  COMMAFMT.C
  3. **
  4. **  Public domain by Bob Stout
  5. **
  6. **  Notes:  1. Use static buffer to eliminate error checks on buffer overflow
  7. **             and reduce code size.
  8. **          2. By making the numeric argument a long and prototyping it before
  9. **             use, passed numeric arguments will be implicitly cast to longs
  10. **             thereby avoiding int overflow.
  11. **          3. Use the thousands grouping and thousands separator from the
  12. **             ANSI locale to make this more robust.
  13. */
  14.  
  15. #include <string.h>
  16. #ifdef TEST
  17.  #include <stdlib.h>
  18. #endif
  19.  
  20. #define NUL '\0'
  21.  
  22. size_t commafmt(char   *buf,            /* Buffer for formatted string  */
  23.                 int     bufsize,        /* Size of buffer               */
  24.                 long    N)              /* Number to convert            */
  25. {
  26.       int len = 1, posn = 1, sign = 1;
  27.       char *ptr = buf + bufsize - 1;
  28.  
  29.       if (2 > bufsize)
  30.       {
  31. ABORT:      *buf = NUL;
  32.             return 0;
  33.       }
  34.  
  35.       *ptr-- = NUL;
  36.       --bufsize;
  37.       if (0L > N)
  38.       {
  39.             sign = -1;
  40.             N = -N;
  41.       }
  42.  
  43.       for ( ; len <= bufsize; ++len, ++posn)
  44.       {
  45.             *ptr-- = (char)((N % 10L) + '0');
  46.             if (0L == (N /= 10L))
  47.                   break;
  48.             if (0 == (posn % 3))
  49.             {
  50.                   *ptr-- = ',';
  51.                   ++len;
  52.             }
  53.             if (len >= bufsize)
  54.                   goto ABORT;
  55.       }
  56.  
  57.       if (0 > sign)
  58.       {
  59.             if (0 == bufsize)
  60.                   goto ABORT;
  61.             *ptr-- = '-';
  62.             ++len;
  63.       }
  64.  
  65.       strcpy(buf, ++ptr);
  66.       return (size_t)len;
  67. }
  68.  
  69. #ifdef TEST
  70.  
  71. main(int argc, char *argv[])
  72. {
  73.       size_t len;
  74.       char buf[20];
  75.       long N;
  76.  
  77.       N = strtol(argv[1], NULL, 10);
  78.       len = commafmt(buf, 20, N);
  79.       printf("%s converts to %s and returned %d\n", argv[1], buf, len);
  80.       return EXIT_SUCCESS;
  81. }
  82.  
  83. #endif
  84.